<!doctype html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link href="/assets/base.css" rel="stylesheet" />
    <link href="/assets/message.css" rel="stylesheet" />
    <title>{% block title %}{{ title|escape }}{% endblock %}</title>
    <script
      src="https://unpkg.com/htmx.org@1.9.6"
      integrity="sha384-FhXw7b6AlE/jyjlZH5iHa/tTe9EpJ1Y55RjcgPbjeWMskSxZt1v9qkxLJWNJaGni"
      crossorigin="anonymous"
    ></script>
    {% block head %}{% endblock %}
  </head>
  <body>
    <!-- prettier-ignore -->
    {% include "components/message.html" %}

    <div id="content">{% block content %}{% endblock %}</div>

    <!-- place for htmx result that are not updating document -->
    <!-- hx-target="#none" -->
    <div id="none" style="display: none"></div>
  </body>
</html>

<script>
  function findButton(event) {
    let button = event.target.querySelector(".button");
    if (button) {
      return button;
    } else {
      return event.target.closest(".button");
    }
  }

  document.body.addEventListener("htmx:beforeRequest", function (event) {
    const closeButton = findButton(event);
    if (closeButton) {
      closeButton.classList.add("loading-button");
      closeButton.disabled = true;
    }
  });

  document.body.addEventListener("htmx:afterRequest", function (event) {
    const closeButton = findButton(event);
    if (closeButton) {
      closeButton.classList.remove("loading-button");
      closeButton.disabled = false;
    }

    const detail = event.detail;
    if (detail.failed) {
      const xhr = detail.xhr;
      displayHttpFail(xhr.status, xhr.statusText, xhr.responseText);
    } else if (detail.target.id === "none") {
      displaySuccess(JSON.parse(detail.xhr.responseText).message);
    }
  });
</script>
